package com.itheima.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

/**
 * @Author itheima
 * @Date 2022/4/24 11:57jdbc.url
 * 目标：通过纯注解对SqlSessionFactoryBean中getObject方法返回对象放入到容器SqlSessionFactory
 * @Bean作用：spring识别某个配置类中带有@Bean方法，调用该@Bean方法，将该方法返回的对象放入到spring容器中
 * @Bean使用场景：第三方类创建对象，统统放入到工厂方法中，然后加上@Bean
 * @PropertySource("classpath:jdbc.properties")作用：加载指定位置的properties文件
 * @MapperScan("com.itheima.dao")作用：扫描接口的包，为接口产生代理对象，该代理对象会放入到spring容器中 掌握！！
 */
@Configuration
@PropertySource("classpath:jdbc.properties")
//3个步骤完成将代理对象放入到spring容器中
@MapperScan("com.itheima.dao")
public class MybatisConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    /**
     * DruidDataSource 放入到容器中
     *
     * @return
     */
    @Bean
    public DataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        System.out.println("datasource工厂方法执行！！");
        return druidDataSource;
    }


    /**
     * sqlSessionFactoryBean.getObject(); 返回的对象放入到spring容器中
     *
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
        return sqlSessionFactory;
    }

    //扫描接口 BrandMapper brandMapper=getMapper(BrandMapper.class)
    //@Bean
    //public static MapperScannerConfigurer mapperScannerConfigurer() {
    //    MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
    //    //扫描UserMapper接口所在包,SqlSessionFactory 到sqlSession.getMapper(UserMapper.class) 产生代理对象，该代理对象也会放入到spring容器中！！
    //    mapperScannerConfigurer.setBasePackage("com.itheima.dao");
    //    return mapperScannerConfigurer;
    //}
}
